# 创建时间:2023/2/5 19:10
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :SavingApi.py
# 基于 Python 3.8.2
# ========================================
# 伪接口，修改设置
# ========================================
from vars import *
import datetime
import pathlib
from Common.Common.common import get_yaml, write_yaml


class Savings:
    def __init__(self):
        """对设置的增改查"""
        self.__initGetData()

    def __initGetData(self):
        self.yaml_path = CONST.PATH.SAVE_DATA_PATH
        self._SaveData: dict = get_yaml(self.yaml_path)

        self._System: dict = self._SaveData['System']
        self._Voice: dict = self._System['Voice']
        self.language: str = self._System['Language']
        self.fps: int = self._System['FPS']
        self.voice_bgm = self._Voice['bgm']
        self.voice_soldier = self._Voice['soldier']
        self.voice_battle = self._Voice['battle']

        self.User: dict = self._SaveData['User']
        self.username: str = self.User['Username']
        self.userRank: int = self.User['Rank']
        self.userRankExp: int = self.User['RankExp']
        self.kanban: str = self.User['Kanban']
        self.kanbanBg: str = self.User['KanbanBg']
        if not pathlib.Path(self.kanbanBg).exists():
            self.kanbanBg = str(CONST.PATH.SCENE_BG_ROOT / self.kanbanBg)
        self.actionPoint: int = self.User['ActionPoint']
        self.money: int = self.User['Money']
        self.gem: int = self.User['Gem']
        self.last_login_time = self.User['LastLoginTime']
        self.last_logout_time = self.User['LastLogoutTime']

        self.HaveBoss: dict = self._SaveData.get('HaveBoss')
        self.HaveHero: dict = self._SaveData['HaveHero']
        self.HaveSoldier: dict = self._SaveData['HaveSoldier']

    def save_all(self):
        """保存所有数据"""
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def get_all_settings(self):
        """获取所有设置"""
        return self._SaveData

    def get_haveCode(self, job):
        """获取一种军士/元帅/boss的所有唯一code"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        if not self.HaveBoss: boss = []
        else: boss = list(self.HaveBoss.keys())
        whatjob = {'boss': boss, 'hero': list(self.HaveHero.keys()), 'soldier': list(self.HaveSoldier.keys())}
        return whatjob[job]

    def get_allLovers(self):
        """获取全部lover"""
        lovers = list()
        for bcode in self.HaveBoss.keys():
            lovers.append(self.HaveBoss[bcode]['lover'])
        for hcode in self.HaveHero.keys():
            lovers.append(self.HaveHero[hcode]['lover'])
        for scode in self.HaveSoldier.keys():
            lovers.append(self.HaveSoldier[scode]['lover'])
        return lovers

    def get_favorEXP(self, job, rolecode) -> int:
        """获取好感度经验值"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]
        return havewhich[rolecode]['lover']['favorEXP']

    def get_favorBg(self, job, rolecode):
        """获取宿舍背景"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]
        bg = havewhich[rolecode]['lover']['favorBg']
        if ':' not in bg:
            bg = str(CONST.PATH.BG_ROOT / bg)
        return bg

    def get_haveRoleDetail(self, job):
        """获取一种军士/元帅/boss的所有战斗code"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]
        if not havewhich: return []

        codes = list()
        if not havewhich: return []
        for scode in havewhich.keys():
            battle: list = havewhich[scode]['battle']
            for role in battle:
                codes.append(role)
        return whatjob[job]

    def get_haveClothesMainCodesAndLevels(self, job):
        """获取拥有的一种军士/元帅/boss服装主code及等级"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]

        clothesCodeLevels = list()
        if not havewhich: return []
        for scode in havewhich.keys():
            lover: dict = havewhich[scode]['lover']
            level = lover['favorLevel']
            favorEXP = lover['favorEXP']
            favorBg = lover['favorBg']
            main = lover['main']
            clothesCodeLevels.append((main, level, job, favorEXP, favorBg))
        return clothesCodeLevels

    def get_haveClothesCodes(self, job):
        """获取拥有的一种军士/元帅/boss服装code"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]

        clothesCodes = list()
        if not havewhich: return []
        for scode in havewhich.keys():
            lover: dict = havewhich[scode]['lover']
            for cloth in lover['clothes']:
                clothesCodes.append(cloth['code'])
        return clothesCodes

    def get_haveTheClothesCodeList(self, job, sCode: str):
        """获取拥有的一个军士/元帅/boss的所有服装code list"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]
        if not havewhich: return []
        clothesCodes = list()
        lover: dict = havewhich[sCode]['lover']
        clothes: list = lover['clothes']
        for cloth in clothes:
            clothesCodes.append(cloth['code'])
        return clothesCodes

    def get_all_haveCodes(self):
        """获取全部：每个角色的code"""
        codes = list()
        boss = self.get_haveCode('boss')
        hero = self.get_haveCode('hero')
        soldier = self.get_haveCode('soldier')
        codes.extend(boss)
        codes.extend(hero)
        codes.extend(soldier)
        return codes

    def get_all_haveMainCodes(self):
        """获取全部：每个角色的主服装code。包括军士、元帅、boss"""
        codes = list()
        boss = self.get_haveClothesMainCodesAndLevels('boss')
        hero = self.get_haveClothesMainCodesAndLevels('hero')
        soldier = self.get_haveClothesMainCodesAndLevels('soldier')
        codes.extend(boss)
        codes.extend(hero)
        codes.extend(soldier)
        # codes.sort(key=lambda x: x[0])
        # codes.sort(key=lambda x: x[-1])
        # codes.sort(key=lambda x: x[1], reverse=True)
        return codes

    def get_all_haveClothesCodes(self):
        """获取全部：每个角色的服装code。包括军士、元帅、boss"""
        clothCodes = list()
        boss = self.get_haveClothesCodes('boss')
        hero = self.get_haveClothesCodes('hero')
        soldier = self.get_haveClothesCodes('soldier')
        clothCodes.extend(boss)
        clothCodes.extend(hero)
        clothCodes.extend(soldier)
        return clothCodes

    def change_theMainCloth(self, job, roleCode, clothCode):
        """更换皮肤"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich: dict = whatjob[job]
        if not havewhich:
            raise KeyError('未获得，不能更换！')
        if roleCode not in self.get_all_haveCodes():
            raise KeyError(f'没有获得该角色！角色code：{roleCode}')
        lover: dict = havewhich[roleCode]['lover']
        if clothCode not in [c['code'] for c in lover['clothes']]:
            raise KeyError(f'未获得该服装！服装code：{clothCode}')
        lover['main'] = clothCode
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def update_favorLevel(self, job, roleCode, level: int, exp: int):
        """更新好感度"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        if roleCode not in self.get_all_haveCodes():
            raise KeyError('没有获得该角色！')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich: dict = whatjob[job]
        if not havewhich:
            raise KeyError('未获得，不能更新好感度！')
        lover: dict = havewhich[roleCode]['lover']
        lover['favorLevel'] = level
        lover['favorEXP'] = exp
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def set_Kanban(self, clothCode, kanbanbg=None):
        """设置主界面看板"""
        if clothCode not in self.get_all_haveClothesCodes():
            raise KeyError('未获得该服装，无法设置看板')
        self.User['Kanban'] = clothCode
        if kanbanbg is not None:
            self.User['KanbanBg'] = kanbanbg
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def add_newCloth(self, job, roleCode, cloth: dict):
        """添加新服装

        :param job: boss/hero/soldier
        :param roleCode: 角色的code
        :param cloth: {'code': 'yzaf', 'describe': '泳装爱芙'}
        :return:
        """
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        whatdata = {'boss': 'HaveBoss', 'hero': 'HaveHero', 'soldier': 'HaveSoldier'}
        havewhich: dict = whatjob[job]
        if not havewhich:
            self._SaveData[whatdata[job]] = {}
            self._SaveData[whatdata[job]][roleCode] = {}
            self._SaveData[whatdata[job]][roleCode]['lover'] = {}
            self._SaveData[whatdata[job]][roleCode]['lover']['main'] = cloth['code']
            self._SaveData[whatdata[job]][roleCode]['lover']['favorLevel'] = 1
            self._SaveData[whatdata[job]][roleCode]['lover']['favorEXP'] = 0
            self._SaveData[whatdata[job]][roleCode]['lover']['favorBg'] = '\scenebg\leader01-1.jpg'
            self._SaveData[whatdata[job]][roleCode]['lover']['clothes'] = [cloth]
            self.save_all()
            self.__initGetData()
            return
        if not havewhich.get(roleCode):
            havewhich[roleCode] = {}
            havewhich[roleCode]['lover'] = {}
            havewhich[roleCode]['lover']['main'] = cloth['code']
            havewhich[roleCode]['lover']['favorLevel'] = 1
            havewhich[roleCode]['lover']['favorEXP'] = 0
            havewhich[roleCode]['lover']['favorBg'] = '\scenebg\leader01-1.jpg'
            havewhich[roleCode]['lover']['clothes'] = [cloth]
            self.save_all()
            self.__initGetData()
            return
        role = havewhich[roleCode]
        if not role.get('lover'):
            role['lover'] = {}
            role['lover']['main'] = cloth['code']
            role['lover']['favorLevel'] = 1
            role['lover']['favorEXP'] = 0
            role['lover']['favorBg'] = '\scenebg\leader01-1.jpg'
            role['lover']['clothes'] = [cloth]
            self.save_all()
            self.__initGetData()
            return
        lover = role['lover']
        clothes = lover['clothes']
        if cloth['code'] in [c['code'] for c in clothes]:
            print('已获得该服装！')
            return
        clothes.append(cloth)
        self.save_all()
        self.__initGetData()
        return

    def add_newRole(self, job, roleCode, role_list: list):
        """添加新角色（战斗）

        :param job: hero/soldier
        :param roleCode: full code
        :param role_list: [{'code': 'af', 'rare': 4, 'name': '爱芙'}]
        :return:
        """
        if job not in ('hero', 'soldier'): raise KeyError(f'job只能为hero/soldier！然而是【{job}】')
        whatjob = {'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        whatdata = {'hero': 'HaveHero', 'soldier': 'HaveSoldier'}
        havewhich: dict = whatjob[job]
        if not havewhich:
            self._SaveData[whatdata[job]] = {}
            self._SaveData[whatdata[job]][roleCode] = {}
            self._SaveData[whatdata[job]][roleCode]['battle'] = []
            battle = self._SaveData[whatdata[job]][roleCode]['battle']
            maxid = 0
        elif not havewhich.get(roleCode):
            havewhich[roleCode] = {}
            havewhich[roleCode]['battle'] = []
            battle = havewhich[roleCode]['battle']
            maxid = 0
        elif not havewhich[roleCode].get('battle'):
            havewhich[roleCode]['battle'] = []
            battle = havewhich[roleCode]['battle']
            maxid = 0
        else:
            battle: list = havewhich[roleCode]['battle']
            maxid = max([b['id'] for b in battle])
        for r in role_list:
            r['id'] = maxid+1
            r['level'] = 1
            r['lock'] = False
            if r['rare'] >= 4:
                r['lock'] = True
            maxid += 1
            battle.append(r)
        self.save_all()
        self.__initGetData()
        return

    def set_cv(self, cv='jp'):
        """设置看板CV为中配或日配"""
        if cv not in ('jp', 'cn'):
            return
        self._System['CV'] = cv
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def set_favorBg(self, job, rolecode, bg):
        """设置宿舍背景"""
        if job not in ('boss', 'hero', 'soldier'): raise KeyError(f'job只能为boss/hero/soldier！然而是【{job}】')
        whatjob = {'boss': self.HaveBoss, 'hero': self.HaveHero, 'soldier': self.HaveSoldier}
        havewhich = whatjob[job]
        havewhich[rolecode]['lover']['favorBg'] = bg
        self.save_all()
        self.__initGetData()

    def set_voice(self, voice: int, which: str):
        """设置音量

        :param voice: 音量大小，百分制
        :param which: 哪个音量（bgm/soldier/battle）
        :return:
        """
        if voice > 100 or voice < 0:
            return
        self._Voice[which] = voice
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def set_username(self, username):
        self.User['Username'] = username
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def set_fps(self, FPS):
        self._System['FPS'] = FPS
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def record_loginTime(self):
        self.User['LastLoginTime'] = datetime.datetime.now()
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()

    def record_logoutTime(self):
        self.User['LastLogoutTime'] = datetime.datetime.now()
        write_yaml(self.yaml_path, self._SaveData)
        self.__initGetData()










